package com.dyj.tiktok.handler;

import com.dyj.common.config.AgentConfiguration;
import com.dyj.common.domain.vo.AccessTikTokTokenVo;
import com.dyj.common.utils.DyConfigUtils;

import java.util.Objects;

public class AccessTokenHandler extends AbstractTikTokHandler {

    public AccessTokenHandler(AgentConfiguration agentConfiguration) {
        super(agentConfiguration);
    }

    public AccessTikTokTokenVo getAccessToken(String code, String redirect_uri) {
        AccessTikTokTokenVo result = getTikTokAuthClient().getAccessToken(agentConfiguration.getClientKey(),agentConfiguration.getClientSecret(), code, "authorization_code", redirect_uri);
        if (Objects.nonNull(result) && Objects.isNull(result.getLogId())) {
            DyConfigUtils.getAgentTokenService().setUserTokenInfo(agentConfiguration.getTenantId(), agentConfiguration.getClientKey(), result.getAccessToken(), result.getExpiresIn(), result.getRefreshToken(), result.getRefreshExpiresIn(), result.getOpenId());
            return result;
        }else{
            return null;
        }
    }

    public AccessTikTokTokenVo refreshToken(String refreshToken, String openId) {
        AccessTikTokTokenVo result = getTikTokAuthClient().refreshToken(agentConfiguration.getClientKey(),agentConfiguration.getClientSecret(), "refresh_token", refreshToken);
        if (Objects.nonNull(result) && Objects.isNull(result.getLogId())) {
            DyConfigUtils.getAgentTokenService().updateRefreshTokenInfo(agentConfiguration.getTenantId(), agentConfiguration.getClientKey(), result.getRefreshToken(), result.getExpiresIn(), openId);
        }
        return result;
    }
}
